<template>
  <view>
    <view class="wrap">
      <input
        class="uni-input"
        placeholder-style="font-size:15px;"
        focus
        v-model="inputVal"
        placeholder="请输入搜索内容"
      />
      <text @click="handleSearch" class="font-weight">搜索</text>
    </view>
    <view class="boxTitle" style="margin-top: 20rpx">
      <view>
        <text
          class="titleClass"
          :class="{ activeClass: title_Name == titleNamObj.login }"
          @click="handleLogin"
          >{{ titleNamObj.login }}</text
        >
      </view>
      <view style="display: flex; align-items: center">
        <text
          class="titleClass"
          :class="{ activeClass: title_Name == titleNamObj.application }"
          @click="handleAppli"
          >{{ titleNamObj.application }}</text
        >
      </view>
    </view>
    <view v-show="title_Name == titleNamObj.login">
      <view
        class="overClass"
        v-if="!isLoading && login.rows.length"
        style="max-height: 85vh"
      >
        <view v-for="item in login.rows" :key="item.id">
          <view class="wrapBox">
            <view class="smallBox">
              <text class="maxwidth"> 危废行业俗称:{{ item.wfTypeName }} </text>
            </view>
            <view class="smallBox">
              <text> 产出日期:{{ item.produceTime }} </text>
              <text> 登记人:{{ memberStore.userName }} </text>
            </view>
            <view class="smallBox">
              <text> 容器/包装类型:{{ item.wfContainerType }} </text>
              <text> 状态:{{ item.wf_Status }} </text>
            </view>
            <view class="smallBox" v-if="item.wfStatus == 3">
              <text> 转运日期:{{ item.transTime }} </text>
              <text> 申请人:{{ item.applyTransUser }} </text>
            </view>
            <view class="smallBox">
              <button
                @click="handleloginlook(item)"
                class="commonBtnClass"
                v-if="item.wfStatus == 2 || item.wfStatus == 3"
              >
                查看
              </button>
            </view>
          </view>
        </view>
      </view>
      <view class="loadingClass" v-show="isLoading">拼命加载中...</view>
      <view class="loadingClass" v-show="!isLoading && !login.rows.length"
        >暂无数据</view
      >
    </view>
    <view v-show="title_Name == titleNamObj.application">
      <view
        class="overClass"
        v-if="!isLoading && appli_cation.rows.length"
        style="max-height: 85vh"
      >
        <view v-for="item in appli_cation.rows" :key="item.id">
          <view class="wrapBox">
            <view class="smallBox">
              <text class="maxwidth"> 危废行业俗称:{{ item.wfTypeName }} </text>
            </view>
            <view class="smallBox">
              <text> 转运日期:{{ item.plan_TransTime }} </text>
              <text> 所属部门:{{ item.deptName }} </text>
            </view>
            <view class="smallBox">
              <text> 去向:{{ item.transTo }} </text>
              <text> 申请人:{{ item.userName }} </text>
            </view>
            <!-- <view class="smallBox" v-show="item.transStatus == 1">
              <text> 当前环节:{{ item.nextActivity }} </text>
              <text> 当前办理人:{{ item.handleUserName }} </text>
            </view> -->
            <view class="smallBox">
              <text :style="{ color: item.transStatus == 2 ? 'red' : '' }">
                审批状态:{{ compStatus(item.transStatus) }}
              </text>
              <button
                @click="handleDetails(item)"
                class="commonBtnClass"
                style="width: 100rpx"
                v-if="item.transStatus != 2"
              >
                查看
              </button>
            </view>
            <view
              class="smallBox"
              style="justify-content: flex-end"
              v-if="item.transStatus == 2"
            >
              <view class="flex-end">
                <button
                  @click="handleLook(item, true)"
                  class="commonBtnClass"
                  :disabled="item.lookDisabled"
                  :loading="item.lookDisabled"
                  style="width: 200rpx"
                >
                  查看转运单22
                </button>
                <button
                  @click="handleLook(item, false)"
                  class="commonBtnClass"
                  :disabled="item.downDisabled"
                  :loading="item.downDisabled"
                  style="width: 200rpx"
                >
                  下载转运单
                </button>
                <button
                  @click="handleDetails(item)"
                  class="commonBtnClass"
                  style="width: 100rpx"
                >
                  查看
                </button>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="loadingClass" v-show="isLoading">拼命加载中...</view>
      <view
        class="loadingClass"
        v-show="!isLoading && !appli_cation.rows.length"
        >暂无数据</view
      >
    </view>
    <l-popup :radius="20" :show="popupShow">
      <view class="width60vw">
        <view style="margin-left: 20rpx; margin-top: 20rpx">{{
          titleName
        }}</view>
        <view style="margin: 20rpx">
          <view class="uni-textarea" style="max-height: 30vh; overflow-y: auto">
            <view
              style="margin-bottom: 20rpx; text-align: center"
              v-for="item in TypeListsName"
              :key="item"
              :class="{ activeClass: activeObj == item }"
              @click="handleClick(item)"
              >{{ item.wfTypeName }}</view
            >
          </view>
          <view class="classBtn">
            <button
              class="commonBtnClass width150rpx mgright20rpx"
              @click="handlebackSure(activeObj, false)"
              :disabled="activeItem?.flag"
              :loading="activeItem?.flag"
            >
              确定
            </button>
            <button class="cancelClass width150rpx" @click="popupShow = false">
              取消
            </button>
          </view>
        </view>
      </view>
    </l-popup>
  </view>
</template>

<script setup>
import lPopup from "@/uni_modules/l-popup/components/l-popup/l-popup.vue";
import { useMemberStore } from "@/stores/modules/member";
import {
  notice_down_pdf,
  show_trans_pdf,
  wfTypeFindPage,
  select_depts_by_deptIds,
  select_user_by_ids,
} from "@/commonApi";
import { basePDFURL, parseTime } from "@/utils";
import { global_search_apply } from "./index";
const titleNamObj = {
  login: "登记信息",
  application: "申请信息",
};
const inputVal = ref("");
const title_Name = ref(titleNamObj.login);
const isLoading = ref(false);
//登记信息
const login = reactive({
  rows: [],
});
//申请信息
const appli_cation = reactive({
  rows: [],
});
const memberStore = useMemberStore();
const popupShow = ref(false);
const TypeListsName = ref([]);
const activeItem = ref(null);
const activeObj = ref(null);
const titleName = ref("");
let isLook = undefined;

const handleLogin = () => {
  if (title_Name.value != titleNamObj.login) {
    title_Name.value = titleNamObj.login;
    // handleSearch();
  }
};
const handleAppli = () => {
  if (title_Name.value != titleNamObj.application) {
    title_Name.value = titleNamObj.application;
  }
  handleSearch();
};
const compStatus = computed(() => {
  return (transStatus) =>
    transStatus == 1
      ? "审批中"
      : transStatus == 2
      ? "已审批"
      : transStatus == 3
      ? "已撤销"
      : transStatus == 4
      ? "信息暂存"
      : "";
});
async function handleSearch() {
  const res = await global_search_apply(
    memberStore.deptMap[0].deptId,
    inputVal.value
  );
  const ress = await wfTypeFindPage();
  const applyDeptIds = res.data.map((item) => item.applyDeptId);
  const depIds = [...new Set(applyDeptIds)].join();
  const promise1 = await select_depts_by_deptIds(depIds);

  const applyUserIds = res.data.map((item) => item.applyUserId);
  const userIds = [...new Set(applyUserIds)].join();
  const promise2 = await select_user_by_ids(userIds);

  res.data.forEach((item) => {
    item.produceTime = parseTime(item.produceTime, "{y}-{m}-{d}");
    item.plan_TransTime = parseTime(item.planTransTime, "{y}-{m}-{d}");
    item.wf_Status =
      item.wfStatus == 1
        ? "未转运"
        : item.wfStatus == 2
        ? "审批中"
        : item.wfStatus == 3
        ? "已转运"
        : item.wfStatus == 4
        ? "转运信息暂存"
        : "";
    //获取危废行业俗称
    if (item.wfType) {
      const typeLists = item.wfType.split(",");
      const TypeNames = [];
      typeLists.forEach((wfType) => {
        const obj1 = ress.data.find((item) => item.id == wfType);
        if (obj1) {
          TypeNames.push(obj1.wfTypeName);
        }
      });
      item.wfTypeName = TypeNames.join(",");
    }
    //获取危废行业俗称

    //部门名字
    const res2 = promise1.data.find((res) => res.deptId == item.applyDeptId);
    if (res2) {
      item.deptName = res2.name;
    }
    //申请人
    const res1 = promise2.data.find((res) => res.userId == item.applyUserId);
    if (res1) {
      item.userName = res1.username;
    }

    const Weights = item.wfTransWeight ? JSON.parse(item.wfTransWeight) : [];
    item.wfTrans_Weight = Weights.length
      ? Weights.reduce((pre, next) => {
          if (next.wfWeight) {
            pre += +next.wfWeight;
          }
          return pre;
        }, 0)
      : "";
  });
  appli_cation.rows = res.data;
}

const handleClick = (item) => {
  activeObj.value = item;
};

const handleLook = (item, flag) => {
  titleName.value = flag ? "查看转运单" : "下载转运单";
  debugger;
  activeItem.value = item;
  isLook = flag;
  TypeListsName.value = [];
  const lists = item.wfTypeName ? item.wfTypeName.split(",") : [];
  TypeListsName.value = lists.map((wfTypeName) => ({
    transCode: item.transCode,
    wfTypeName,
    applyId: item.applyId,
  }));
  if (TypeListsName.value.length == 1) {
    handlebackSure(item, true);
  } else {
    if (TypeListsName.value.length > 1) {
      popupShow.value = true;
      activeObj.value = TypeListsName.value[0];
    }
  }
};
const handlebackSure = async (item, isLine) => {
  if (isLook) {
    try {
      if (isLine) {
        item.lookDisabled = true;
      } else {
        activeItem.value.flag = true;
      }
      await show_trans_pdf(item.applyId, encodeURIComponent(item.wfTypeName));
    } catch (err) {
      memberStore.srcURL = `${basePDFURL}/trans_pdf/${
        item.transCode
      }-${encodeURIComponent(item.wfTypeName)}.pdf`;
      uni.navigateTo({
        url: `/pages/PdfShow/PdfShow`,
      });
    } finally {
      if (isLine) {
        item.lookDisabled = false;
      } else {
        activeItem.value.flag = false;
      }
    }
  } else {
    try {
      if (isLine) {
        item.downDisabled = true;
      } else {
        activeItem.value.flag = true;
      }
      await notice_down_pdf(
        item.applyId,
        encodeURIComponent(item.wfTypeName),
        memberStore.userInfo.userIdDing
      );
      item.downDisabled = false;
      uni.showToast({ icon: "success", title: "下载成功" });
    } finally {
      if (isLine) {
        item.downDisabled = false;
      } else {
        activeItem.value.flag = false;
      }
    }
  }
  popupShow.value = false;
};
const handleDetails = (item) => {
  memberStore.QueryTransferDetails = JSON.parse(JSON.stringify(item));
  uni.navigateTo({
    url: `/pages/QueryTransferDetails/QueryTransferDetails`,
  });
};
const handleloginlook = (item) => {
  memberStore.RegisterObjViewing = JSON.parse(JSON.stringify(item));
  uni.navigateTo({
    url: `/pages/RegisterViewing/RegisterViewing`,
  });
};
</script>

<style lang="scss" scoped>
.wrap {
  display: flex;
  justify-content: center;
  margin-top: 50rpx;
  align-items: center;
}
.uni-input {
  background-color: #e9e2e2;
  margin-right: 20rpx;
  width: 70vw;
}
.boxTitle {
  padding: 10px 20px;
  display: flex;
  justify-content: space-around;
}
.yuanClass {
  box-sizing: border-box;
  text-align: center;
  background: red;
  color: #fff;
  border-radius: 2000rpx;
  padding: 0 0.5em;
  min-width: 60rpx;
  height: 60rpx;
  line-height: 60rpx;
  margin-left: 10rpx;
}
.titleClass {
  font-weight: bolder;
}
</style>